package org.project.choujiang.utils;

import org.project.choujiang.pojo.domain.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class TokenUtils {
    private static Map<String, User> userMap = new HashMap<>();

    private static ThreadLocal<String> uuidMap = new ThreadLocal<>();

    public static String login(User user){
        String uuid = UUID.randomUUID().toString();
        userMap.put(uuid,user);
        return uuid;
    }

    public static User getLoginUserInfo(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        if (request != null) {
            // 从请求头中获取 token
            String token = request.getHeader("Authorization");
            return userMap.get(token);
        }

        throw new IllegalArgumentException("请先登录");
    }

    public static void dengluInit(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        if (request != null) {
            // 从请求头中获取 token
            String token = request.getHeader("Authorization");
            uuidMap.set(token);
        }
        throw new IllegalArgumentException("请先登录");
    }
}
